package business;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.example.bankdb.BanKInfo;
import org.example.bankdb.ObjectFactory;

public class BankRepository {
	private static final String file_path = "../datasource/ds_6_3.xml";
	public static Marshaller marshaller;
	public static Unmarshaller unmarshaller;
	public static File file;
	//private File file = new File("ds_1_3.xml");
	//private JAXBContext context;
	
	public BankRepository() throws JAXBException{
		
		if (unmarshaller == null || marshaller == null) {
			//context = JAXBContext.newInstance(BanKInfo.class);
			// create the context on package
			//JAXBContext jc = JAXBContext.newInstance("org.example.bankdb");//, ObjectFactory.class.getClassLoader());
			
		    ClassLoader cl = org.example.bankdb.ObjectFactory.class.getClassLoader();
		    String packageName = BanKInfo.class.getPackage().getName();
		    JAXBContext jc = JAXBContext.newInstance(packageName, cl);
			
			// create marshaller and unmarshaller using context
			unmarshaller = jc.createUnmarshaller();
			marshaller = jc.createMarshaller();
			file = new File(file_path);
		}
	}
	
	public BanKInfo GetBank() throws JAXBException{		
		BanKInfo bank = unmarshal();
		if (bank == null)
			bank = new BanKInfo();		
		return bank;
	}
	
	public void SaveBank(BanKInfo bankInfo) throws JAXBException{	
		marshal(bankInfo);
	}
		
	private static BanKInfo unmarshal()
	{
		if (file.exists())
		{
			JAXBElement<BanKInfo> unmarshallObject = null;
			try {
				unmarshallObject = (JAXBElement<BanKInfo>)unmarshaller.unmarshal(new File(file_path));
			} catch (JAXBException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return unmarshallObject.getValue();
		}
		
		return null;
	}
	
	private static void marshal(BanKInfo bank)
	{		
		ObjectFactory obf = new ObjectFactory();
		JAXBElement<BanKInfo> output = obf.createBank(bank);
		try {
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
			marshaller.marshal(output, new FileOutputStream(file_path));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
